package com.appkubes.portal.admin.application.auth.service.impl;

import com.appkubes.portal.admin.application.auth.service.KeyCloakService;
import lombok.extern.slf4j.Slf4j;
import org.keycloak.OAuth2Constants;
import org.keycloak.admin.client.Keycloak;
import org.keycloak.admin.client.KeycloakBuilder;
import org.keycloak.admin.client.resource.ClientResource;
import org.keycloak.admin.client.resource.RealmResource;
import org.keycloak.admin.client.resource.UserResource;
import org.keycloak.representations.idm.ClientRepresentation;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
@Slf4j
public class KeyCloakServiceImpl implements KeyCloakService {
    //管理客户端信息
    @Value("${portal.keycloak.serverUrl}")
    String serverUrl;

    @Value("${portal.keycloak.adminRealm}")
    String adminRealm;

    @Value("${portal.keycloak.adminUserName}")
    String username;

    @Value("${portal.keycloak.adminPassword}")
    String password;


    //当前连接的客户端
    @Value("${keycloak.realm}")
    String currentRealm;
    @Value("${keycloak.resource}")
    String clientId;

    @Override
    public Keycloak getKeycloak() {
        Keycloak keycloak = KeycloakBuilder.builder()
                .serverUrl(serverUrl)
                .grantType(OAuth2Constants.PASSWORD) //
                .realm(adminRealm)
                .username(username)
                .password(password)
                .clientId("admin-cli")
                .build();
        return keycloak;
    }

    @Override
    public RealmResource getRealmResource() {
        Keycloak keycloak = getKeycloak();
        return keycloak.realm(currentRealm);
    }

    @Override
    public ClientResource getClientResource() {
        List<ClientRepresentation> clients = getRealmResource().clients().findByClientId(clientId);
        return clients == null ? null : getRealmResource().clients().get(clients.get(0).getId());

    }

    @Override
    public UserResource getUserResource(String userId) {
        return this.getRealmResource().users().get(userId);
    }

    @Override
    public String getAccessToken() {
        // 取得accesstoken
        String accessToken = getKeycloak().tokenManager().getAccessTokenString();
        return accessToken;
    }


}
